#!/usr/bin/env python
# -*- coding: utf-8 -*-


from PyQt4 import QtCore, QtGui
from Ui_login import Ui_LoginDialog
from Ui_about import Ui_Dialog

import sys
import httplib
import time
import threading
import thread
import getpass
import socket
from xml.dom import minidom
#from string import Template
import os
import sip


import TinyHTTPProxy

version = '0.0.12'
timeout = 3
configFile = os.path.expanduser('~/.qpypassport/config')
isOut = True
isProxy = False

#check whether can reach the Passport Server and return Local IP
def checkNetwork_getIP():
    ###checkNetWork
    socket.setdefaulttimeout(timeout)
    try:
        conn = httplib.HTTPConnection("auth.stu.edu.cn")
        conn.request('GET','/')
        resp = conn.getresponse()
    except Exception:
        print "Cannot reach the NC server"
        return False

    ### get local IP address
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    port = socket.getservbyname('http', 'tcp')
    s.settimeout(timeout)
    try:
        s.connect(("auth.stu.edu.cn", port))
    except socket.error, e:
         #print "Connection Error: %s" %e
         #print "Can not connet to STU passport Server"
         #print "Please check your network."
         s.close()
         return False
    except socket.time:
         print "Connot to STU passprot timeout..."
         print "Please check the network."
         s.close()
         return False
         #sys.exit(1)
    ipAndPort = s.getsockname()
    ip = ipAndPort[0]
    s.close()
    return ip

#getTag value in XML
def getTagText(root, tag):
    node = root.getElementsByTagName(tag)[0]
    rc = ""
    for node in node.childNodes:
        if node.nodeType in ( node.TEXT_NODE, node.CDATA_SECTION_NODE):
            rc = rc + node.data
    return rc


#password secure
def jiami(password):
    passlist = map((lambda x: ord(str(x))), password)
    passlist2 = []
    for i in passlist:
        if int(i)< 100:
            i = int(i) + 888
        passlist2.append(i)
    securePassword = ''
    for j in passlist2:
        securePassword = securePassword + str(j)
    securePassword = hex(long(securePassword))[2:-1]
    return securePassword

def jiemi(securePassword):
    securePassword = int(securePassword, 16)
    #print securePassword
    passlist = []
    for i in range(0, len(str(securePassword)),3):
        x = 0; y = 3
        x = x + i; y = y + i
        word = str(securePassword)[x:y]
        #print word
        if int(word) >= 800:
            word = int(word)-888
        passlist.append(int(word))
    passlist2 = map((lambda x: chr(x)), passlist)
    password = ''
    for j in passlist2:
        password = password + str(j)
    return password

#function login...
def login(account, password, ip):
    LoginMsg = """<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ClientLogon xmlns="http://tempuri.org/">
<userName>%s</userName>
<password>%s</password>
<userIp>%s</userIp>
<hostName>everest Linux</hostName>
<userMac>00:00:00:00</userMac>
<userAgent>pypassport</userAgent>
<isVisiteForeign>true</isVisiteForeign>
</ClientLogon>
</soap:Body>
</soap:Envelope>
"""
    LoginMessage = LoginMsg%(account, password, ip)
    #print type(account)
    #print LoginMessage

    ###construct and send the header
    socket.setdefaulttimeout(timeout)
    try:
        p_webservice = httplib.HTTPS("auth.stu.edu.cn")
        p_webservice.putrequest("POST", "/netfilter/UserLogon.asmx")
        p_webservice.putheader("Host", "auth.stu.edu.cn")
        #p_webservice.putheader("User-Agent", "Borland SOAP 1.2")
        p_webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        p_webservice.putheader("Content-length", "%d" % len(LoginMessage))
        #p_webservice.putheader("Cache-Control", "no-cache")
        #p_webservice.putheader("Connection", "Keep-Alive")
        p_webservice.putheader("SOAPAction", "\"http://tempuri.org/ClientLogon\"")
        p_webservice.endheaders()
        p_webservice.send(LoginMessage)
    except socket.timeout:
        print "Connect to STU NC Server TIMEOUT when Login, Now exiting....OK"
        p_webservice.close()
        #sys.exit(1)
    except:
        print "Network ERROR When Login....Please check your network configure"
        print "Now exiting...............OK!"
        p_webservice.close()
        #sys.exit(1)

    ### get the response from server
    statuscode, statusmessage, header = p_webservice.getreply()
    #print "Response: ", statuscode, statusmessage
    #print "headers: ", header
    res = p_webservice.getfile().read()
    p_webservice.close()
    #print "Login res:%s" % res
    xmldoc = minidom.parseString(res)
    root = xmldoc.documentElement
    tag = 'ClientLogonResult'
    loginResult = getTagText(root, tag)
    print loginResult
    return loginResult #return the login code
def logout(account, ip):
    LogoutMsg = """<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<logout xmlns="http://tempuri.org/">
<userName>%s</userName>
<userIp>%s</userIp>
<isOutSide>true</isOutSide>
</logout>
</soap:Body>
</soap:Envelope>
"""
    LogoutMessage = LogoutMsg%(account, ip)
    #print LogoutMessage

    #construct and send the header
    socket.setdefaulttimeout(timeout)
    try:
        p_webservice = httplib.HTTPS("auth.stu.edu.cn")
        p_webservice.putrequest("POST", "/netfilter/UserLogon.asmx")
        p_webservice.putheader("Host", "auth.stu.edu.cn")
        p_webservice.putheader("User-Agent", "Borland SOAP 1.2")
        p_webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        p_webservice.putheader("Content-length", "%d" % len(LogoutMessage))
        p_webservice.putheader("Cache-Control", "no-cache")
        #p_webservice.putheader("Connection", "Keep-Alive")
        p_webservice.putheader("SOAPAction", "\"http://tempuri.org/logout\"")
        p_webservice.endheaders()
        p_webservice.send(LogoutMessage)
    except socket.timeout:
        print "Connect to STU NC Server TIMEOUT when logouting, Now exiting....OK"
        p_webservice.close()
        return False
    except:
        print "Network ERROR when logouting....Please check your network configure"
        print "Now exiting...............OK!"
        p_webservice.close()
        return False

    # get the response from server
    statuscode, statusmessage, header = p_webservice.getreply()
    #print "Response: ", statuscode, statusmessage
    #print "headers: ", header
    res = p_webservice.getfile().read()
    p_webservice.close()
    #print res
    return True
def keepActive(account, password, ip):
    KeepMsg = """<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<keepUserActive xmlns="http://tempuri.org/">
<userName>%s</userName>
<isOutSide>true</isOutSide>
<userAgent>pypassport</userAgent>
</keepUserActive>
</soap:Body>
</soap:Envelope>
"""

    KeepMessage = KeepMsg%(account)
    #print KeepMessage

    #construct and send the header
    socket.setdefaulttimeout(timeout)
    try:
        p_webservice = httplib.HTTPS("auth.stu.edu.cn")
        p_webservice.putrequest("POST", "/netfilter/UserLogon.asmx")
        p_webservice.putheader("Host", "auth.stu.edu.cn")
        #p_webservice.putheader("Connection", "Keep-Alive")
        p_webservice.putheader("User-Agent", "Borland SOAP 1.2")
        p_webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        p_webservice.putheader("Content-length", "%d" % len(KeepMessage))
        p_webservice.putheader("Cache-Control", "no-cache")
        p_webservice.putheader("SOAPAction", "\"http://tempuri.org/keepUserActive\"")
        p_webservice.endheaders()
        p_webservice.send(KeepMessage)
    except socket.timeout:
        print
        print "Connect to STU NC Server TIMEOUT when keepActive..."
        p_webservice.close()
        return False
    except:
        print
        print "Network ERROR when keepActive....Please check your network configuration!"
        p_webservice.close()
        return False
        #sys.exit(1)
    # get the response from Server
    statuscode, statusmessage, header = p_webservice.getreply()
    #print "Response: ", statuscode, statusmessage
    #print "headers: ", header
    res = p_webservice.getfile().read(371)
    p_webservice.close()
    #print res
    xmldoc = minidom.parseString(res)
    root = xmldoc.documentElement
    tag = 'keepUserActiveResult'
    keepActive = getTagText(root, tag)
    if '100' == keepActive and not isOut:#在本机上还没按注销按钮才进行重新登录
        print "You have logout......"
        #return False
        loginAgain = forceLogin(account, password, ip)
        if loginAgain == '222':
            print "OK...You have Login again! Press 'Enter' for more help"
            return True
        else:
            return False
    elif '100' == keepActive:
        print "You have logout....in local machine"
        return False
    else:
        return True
def loopKeep(account, password, ip, sleeptime, *args):
    time.sleep(sleeptime)
    k = keepActive(account, password, ip)
    if not k:
       #print "Trying again...Please wait...."
       #print "If you give up to trying, press 'q' to quit, More help Press 'Enter' !"
       print "exit...keepActive"
       del k
       sys.exit(1)

def forceLogin(account, password, ip):
    logoutR = False
    while not logoutR:
        logoutR = logout(account, ip)
    fLoginC = login(account, password, ip)
    return fLoginC
### If only keepActive, sometimes it can not reach the Internet will happen, but According to
### http://auth.stu.edu.cn/campusAccount/searchIn3.aspx   It also at login status.
#### bug ???
### keepCheck will logout and then login to solve this problem....
def keepCheck(account, password, ip, sleeptime, *args):
    #print isOut
    time.sleep(sleeptime)
    timeout = 1
    socket.setdefaulttimeout(timeout)
    try:
        conn = httplib.HTTPConnection("www.baidu.com")
        conn.request('GET','/')
        resp = conn.getresponse()
    except Exception:
        print "Cannot reach the Internet....."
        while True:
            if not isOut:
                print "Now, logout and then login.........",
                fLogin = forceLogin(account, password, ip)
                if fLogin == '222':
                    print "OK"
                    break
                else:
                    print "Cannot login again, Unknow ERROR, Maybe Network!"
                    break
            else:#when logout, isOut is True
                print "Because you have logout! Now exit the keepCheck thread..."
                sys.exit(1)#exit the thread...
                break


def getFlow(account):
    GetFlowMsg = """<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetFlow xmlns="http://tempuri.org/">
<UserName>%s</UserName>
</GetFlow>
</soap:Body>
</soap:Envelope>
"""
    GetFlowMessage = GetFlowMsg%(account)
    #print GetFlowMessage

    #construct and send the header
    socket.setdefaulttimeout(timeout)
    try:
        p_webservice = httplib.HTTPS("auth.stu.edu.cn")
        p_webservice.putrequest("POST", "/netfilter/UserLogon.asmx")
        p_webservice.putheader("Host", "auth.stu.edu.cn")
        p_webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        #p_webservice.putheader("Connection", "Keep-Alive")
        #p_webservice.putheader("User-Agent", "Borland SOAP 1.2")
        p_webservice.putheader("Content-length", "%d" % len(GetFlowMessage))
        #p_webservice.putheader("Cache-Control", "no-cache")
        p_webservice.putheader("SOAPAction", "\"http://tempuri.org/GetFlow\"")
        p_webservice.endheaders()
        p_webservice.send(GetFlowMessage)
    except socket.timeout:
        print
        print "Connect to STU NC Server TIMEOUT when GetFlow, Now exiting....OK"
        print "Trying again...Please wait...."
        print "If you give up to trying, press 'q' to quit, More help Press 'Enter' !"
        p_webservice.close()
        return False
    except Exception:
        print
        print "Network ERROR when GetFlow....Please check your network configure"
        print "Trying again...Please wait...."
        #print "If you give up to trying, press 'q' to quit, More help Press 'Enter' !"
        p_webservice.close()
        return False


    # get the response from Server
    statuscode, statusmessage, header = p_webservice.getreply()
    #print "Response: ", statuscode, statusmessage
    #print "headers: ", header
    res = p_webservice.getfile().read()
    p_webservice.close()
    #print res
    xmldoc = minidom.parseString(res)
    root = xmldoc.documentElement
    tag = 'DayFlow'
    dayflow = getTagText(root, tag)
    tag = 'DayFlowTotal'
    dayTotal = getTagText(root, tag)
    print "    DayFlow: %sM/%sM" % (dayflow, dayTotal)
    tag = 'MonthFlow'
    monthflow = getTagText(root, tag)
    tag = 'MonthFlowTotal'
    monthTotal = getTagText(root, tag)
    print "    MonthFlow: %sM/%sM" % (monthflow, monthTotal)
    flowInfo = [dayflow, dayTotal, monthflow, monthTotal]
    return flowInfo


def savePassword(account, password):
        if os.path.isdir(os.path.split(configFile)[0]):  #configFile directory is exits
            if os.path.isfile(configFile):  #configFile is exits
                fobjr = open(configFile, 'r', -1)
                all = fobjr.readlines()
                fobjr.close()
                #allInfo = [ line.replace(os.linesep, '', 1) for line in all ]
                account = jiami(account)+ os.linesep
                password = jiami(password) + os.linesep
                if account in all:
                    indexAccount = all.index(account)
                    oldPassword = all[indexAccount + 1]
                    all.remove(oldPassword)
                    all.insert(indexAccount+1, password)
                    fobjw = open(configFile, 'w', -1)
                    fobjw.writelines(all)
                    fobjw.close()
                    os.chmod(configFile, 0600)
                    print "password havs updated...."
                    return True
                else:
                    fobja = open(configFile, 'a', -1)
                    fobjw.write(jiami(account) + os.linesep)
                    fobjw.write(jiami(password) + os.linesep)
                    fobjw.write('False' + os.linesep)
                    fobjw.close()
                    print "New account has added..."
                    return True
            else:  #configFile is not exit but its directory is exits
                fobjw = open(configFile, 'w', -1)
                fobjw.write(jiami(account) + os.linesep)
                fobjw.write(jiami(password) + os.linesep)
                fobjw.write('False' + os.linesep)
                fobjw.close()
                os.chmod(configFile, 0600)
                print "configFile has Build..."
                return True

        else:  #configFile directory and configFile are not exit
            os.mkdir(os.path.split(configFile)[0])
            os.chmod(os.path.split(configFile)[0], 0700)
            fobjw = open(configFile, 'w', -1)
            fobjw.write(jiami(account) + os.linesep)
            fobjw.write(jiami(password) + os.linesep)
            fobjw.write('False' + os.linesep)
            fobjw.close()
            os.chmod(configFile, 0600)
            print "ConfigFile and its directory are builded."
            return True

class MyThread(threading.Thread):

    def __init__(self, func, args, name = ''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        self.over = False
    def run(self):
        while not isOut:
            apply(self.func, self.args)
            if self.over:#??? bug? can't be run??
                print "exit....Threading.."
                sys.exit(1)
    def kill(self):
        self.over = True

class About(QtGui.QDialog):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.hide)
        #self.show()
        

class QPyPassport(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_LoginDialog()
        self.ui.setupUi(self)
        self.resize(333, 221)
        self.setMaximumSize(QtCore.QSize(333, 221))
        self.setMinimumSize(QtCore.QSize(333, 221))
        self.setWindowTitle(QtGui.QApplication.translate("LoginDialog", "Qpypassport %s" % version, None, QtGui.QApplication.UnicodeUTF8))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/Qpypassport.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)



        self.centerUi()

        self.createTrayActions()
        self.createTrayIcon()
        #self.trayIcon.show()

        QtCore.QObject.connect(self.ui.pB_inOut, QtCore.SIGNAL("clicked()"), self.pB_inOutAction)
        QtCore.QObject.connect(self.ui.pB_getFlow, QtCore.SIGNAL("clicked()"), self.pB_getFlowAction)
        QtCore.QObject.connect(self.ui.pB_outClose, QtCore.SIGNAL("clicked()"), self.pB_outCloseAction)
        QtCore.QObject.connect(self.ui.pB_about, QtCore.SIGNAL("clicked()"), self.pB_aboutAction)
        QtCore.QObject.connect(self.ui.pB_Close, QtCore.SIGNAL("clicked()"), self.pB_CloseAction)
        QtCore.QObject.connect(self.ui.pB_proxy, QtCore.SIGNAL("clicked()"), self.pB_proxyAction)
        
        QtCore.QObject.connect(self.ui.cB_account, QtCore.SIGNAL("currentIndexChanged(int)"), self.cB_accountAction)
        
        QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.trayActive)

        if os.path.isfile(configFile):
            fobjr = open(configFile, 'r', -1)
            all = fobjr.readlines()
            accountAndpassword = [ line.replace(os.linesep, '', 1) for line in all ]
            #for i, info in enumerate(accountAndpassword):
            i = 0
            self.accountList = []
            self.passwordList = []
            while i < len(accountAndpassword):
                account = jiemi(accountAndpassword[i])
                print account
                self.accountList.append(account)
                #print accountList
                self.passwordList.append(jiemi(accountAndpassword[i+1]))
                #autoList = autoList.append(accountAndpassword[i+2])
                i = i + 3
            print self.accountList
            self.ui.cB_account.addItems(self.accountList)
            
            #account = jiemi(accountAndpassword[0])
            #password = jiemi(accountAndpassword[1])
            #self.ui.lE_account.setText(account)
            #self.ui.lE_password.setText(password)
        else:
            account = ''
            password = ''
            #self.ui.lE_account.setText(account)
            self.ui.cB_account.setEditText(account)
            self.ui.lE_password.setText(password)
    def cB_accountAction(self, index):
        print index
        print self.ui.cB_account.itemText(index)
        password = self.passwordList[index]
        #print password
        self.ui.lE_password.setText(password)
    
    def createTrayActions(self):
        self.getFlowAction = QtGui.QAction(u"查询流量",self)
        self.getFlowAction.setIcon(QtGui.QIcon("images/find.png"))
        self.outCloseAction = QtGui.QAction(u"注销并关闭", self)
        self.outCloseAction.setIcon(QtGui.QIcon("images/logout.png"))
        self.aboutAction = QtGui.QAction(u"关于",self)
        self.aboutAction.setIcon(QtGui.QIcon("images/about.png"))
        self.quitAction = QtGui.QAction(u"退出", self)
        self.quitAction.setIcon(QtGui.QIcon("images/exit.png"))

        
        QtCore.QObject.connect(self.getFlowAction, QtCore.SIGNAL("triggered()"),  self.pB_getFlowAction)
        QtCore.QObject.connect(self.outCloseAction, QtCore.SIGNAL("triggered()"), self.pB_outCloseAction)
        QtCore.QObject.connect(self.aboutAction, QtCore.SIGNAL("triggered()"),  self.pB_aboutAction)
        QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"),QtGui.qApp, QtCore.SLOT("quit()"))

    def createTrayIcon(self):
        self.trayIconMenu = QtGui.QMenu(self)
        
        self.trayIconMenu.addAction(self.getFlowAction)
        self.trayIconMenu.addAction(self.outCloseAction)
        self.trayIconMenu.addAction(self.aboutAction)
        self.trayIconMenu.addAction(self.quitAction)
        
        self.trayIcon = QtGui.QSystemTrayIcon(self)

        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.setIcon(QtGui.QIcon("images/Qpypassport.png"))
         
        self.trayIcon.setToolTip('Qpypassport %s' % version)
       
       
    

    def centerUi(self):
        screen = QtGui.QDesktopWidget().screenGeometry() #获取显示器分辨率
        size = self.geometry() #获得窗体大小
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)


    def pB_inOutAction(self):
        ##print "login..or...out..."
        #account = str(self.ui.lE_account.text())
        account = str(self.ui.cB_account.currentText())
        password = str(self.ui.lE_password.text())
        if account=='':
            QtGui.QMessageBox.warning(None, u'请输入帐号', u"帐号不能为空，请输入帐号", u"确定")
            return
        if password == '':
            QtGui.QMessageBox.warning(None, u'请输入密码', u"密码不能为空，请输入密码", u"确定")
            return
        ip = checkNetwork_getIP()
        #print account, password, ip
        if ip == False:
            reachError = u'连接不到NC服务器，请检查网络!'
            QtGui.QMessageBox.warning(None, reachError, reachError, QtGui.QMessageBox.Ok)
            return
        global isOut
        #print isOut
        #t_keepCheck = MyThread(keepCheck, (account, password, ip, 2))
        #t_keep = MyThread(loopKeep, (account, password, ip, 60))
        if isOut:
            loginC = login(account, password, ip)
            while '222' != loginC:
                if loginC == '000':
                    print "Account, ERROR...."
                    #self.ui.lE_account.clear()
                    self.ui.cB_account.lineEdit().clear()
                    accountErrorTitle = u'帐号错误'
                    accountErrorContent = u'帐号输入错误，或者帐号还没开通，请从新输入帐号!'
                    QtGui.QMessageBox.warning(None, accountErrorTitle, accountErrorContent, u"确定")
                    break
                elif loginC == '001':
                    print "password ERROR..."
                    passwordErrorTitle = u'密码错误'
                    passwordErrorContent = u"密码输入有误，请从新输入，如果需要更改密码请浏览:\nhttp://netms.stu.edu.cn/ModifyPassword.aspx"
                    QtGui.QMessageBox.warning(None, passwordErrorTitle, passwordErrorContent, u"确定")
                    self.ui.lE_password.clear()
                    #if account in self.accountList:
                        #global updatePassword
                        #updatePassword = True
                    break
                elif loginC == '002':
                    print "Account or IP are Occupied!!"
                    occupyErrorTitle = u'帐号，或者IP被占用'
                    occupyErrorContent = u'帐号或者IP被占用，需要强制登录吗？'
                    forceL = QtGui.QMessageBox.warning(None, occupyErrorTitle, occupyErrorContent, u"需要", u"不需要")
                    print forceL
                    if 0 == forceL:
                        loginC = forceLogin(account, password, ip)
                    else:
                        break
                elif loginC == '231':
                    flowError =  u"帐号%s本日流量已经用完！" % account
                    print flowError
                    QtGui.QMessageBox.warning(None, u"流量警告", flowError, u"确定")
                    break
                else:
                    print "Unknow ERROR...Please try it late!!"
                    unknowErrorTitle = u'未知错误'
                    unknowErrorContent = u'未知错误，请检查您的帐号使用情况'
                    QtGui.QMessageBox.warning(None, unknowErrorTitle, unknowErrorContent, u"确定")
                    break
                    #sys.exit(1)

            if '222' == loginC:
                print "Login Successed!!"
                self.ui.pB_inOut.setText(u'注销')
                onlineText = u"帐号&nbsp;<font color = blue>%s</font><b>&nbsp;在线</b>" % account
                self.ui.l_status.setText(onlineText)
                #self.ui.l_status.setText(u'帐号%s 在线' % account)
                #self.ui.lE_account.setReadOnly(True)
                #self.ui.cB_account.setEditText(account)
                #self.ui.cB_account.setEditable(False)
                self.ui.cB_account.setEnabled(False)
                #self.ui.lE_password.setReadOnly(True)
                self.ui.lE_password.setEnabled(False)
                self.ui.cB_rememberPassword.setEnabled(False)
                isOut = False
                self.ui.pB_outClose.setText(u"注销并关闭")
                self.ui.pB_outClose.setEnabled(True)
                self.ui.pB_proxy.setEnabled(True)
                #self.pB_outClose.setEnabled(1)
                global t_keepCheck
                global t_keep
                t_keepCheck = MyThread(keepCheck, (account, password, ip, 3))
                t_keep = MyThread(loopKeep, (account, password, ip, 60))
                t_keepCheck.setDaemon(True)
                t_keepCheck.start()
                t_keep.setDaemon(True)
                t_keep.start()
                #QtGui.QMessageBox.information(None, "Login Successed", u"登录成功", QtGui.QMessageBox.Ok)
                if self.ui.cB_rememberPassword.isChecked():
                    saveInfo = savePassword(account, password)
                    print saveInfo
                    del saveInfo
                else:
                    print "Not remember password."

        else:
            print "Logout....",
            logoutR = logout(account, ip)
            if logoutR:
                print "...OK"
                isOut = True
                t_keepCheck.kill()
                t_keep.kill()
                self.ui.pB_inOut.setText(u'登录')
                self.ui.l_status.setText(u'离线')
                self.ui.pB_outClose.setEnabled(False)
                self.ui.cB_account.setEnabled(True)
                self.ui.cB_account.setEditable(True)
                self.ui.lE_password.setReadOnly(False)
                self.ui.lE_password.setEnabled(True)
                self.ui.cB_rememberPassword.setEnabled(True)
                #sys.exit(1)



    def pB_getFlowAction(self):
        print "getFlow..."
        print "Flow..."
        print "isProxy=%s" % isProxy
        #account = str(self.ui.lE_account.text())
        account = str(self.ui.cB_account.currentText())
        print account
        flowList = getFlow(account)
        #print flowList
        if not flowList:
            QtGui.QMessageBox.warning(None, u"查不到", u"暂时查不到相关信息，请稍后再查!", u"确定")
        else:
            dayUsed = flowList[0]
            dayTotal = flowList[1]
            monthUsed = flowList[2]
            monthTotal = flowList[3]
            flowInfo = u'帐号:%s的流量信息\n\n日流量信息: %sM/%sM \n月流量信息: %sM/%sM' % (account, dayUsed, dayTotal, monthUsed, monthTotal)
            confirm = QtGui.QMessageBox.information(None, u"流量信息", flowInfo, u"确定")
            print confirm
        if self.trayIcon.isVisible() and not self.isVisible():  ##避免由于关掉MessageBox引起主程序也关掉
            self.show()
            self.hide()
            self.trayIcon.show()
            

    def pB_outCloseAction(self):
        print "out....close"
        if isOut:
            print "exiting....."
            sys.exit(1)
        else:
            print "Logout and quit..."
            ip = checkNetwork_getIP()
            #account = str(self.ui.lE_account.text())
            account = str(self.ui.cB_account.currentText())
            logoutR = logout(account, ip)
            if logoutR:
                print "...logout..ok"
                sys.exit(1)
            else:
               print "can't reach NC service..Now exit without logout.."
               sys.exit(1)


    def pB_aboutAction(self):
        #self.hide()
        #about = About()
        #about.setupUi(about)
        #self.centerUi()
        #about.show()
        
        #print "about..."
        d = QtGui.QDialog()
        aboutD = Ui_Dialog()
        aboutD.setupUi(d)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/about.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        d.setWindowIcon(icon)

        d.show()
        d.exec_()
        #aboutD.show()
        
        print "about..."
        #self.show()
        
    def pB_CloseAction(self):
        sys.exit(1)
    
    def closeEvent(self, event):
        print "close..."
        if isOut:
            event.accept()
        else:
            if self.trayIcon.isSystemTrayAvailable():
                self.trayIcon.show()
                self.hide()
                event.ignore()
            else:
                closePro = QtGui.QMessageBox.warning(None, u'还没注销帐号', u'帐号还没注销\n真的需要直接关闭本程序吗？', u"需要", u"不需要")
                if 0 == closePro:
                    event.accept()
                else:
                   event.ignore()

    def trayActive(self, reason):
        #print "active.."
        if reason == QtGui.QSystemTrayIcon.Trigger:
            self.show()
            #self.setVisible(True)
            #self.showNormal()
            #self.setFocus()
            ##self.setVisible(True)
            #self.trayIcon.hide()
    def pB_proxyAction(self):
        print "proxy"
        global isProxy
        print isProxy
        if not isOut and not isProxy:
            ipstr = str(self.ui.lE_proxy.text())
            #print ipstr
            iplist = ipstr.split(";") #多个IP可以用;号隔开
            for oneIP in iplist:
                if not oneIP.startswith('10.'): ##校内ip开头为 10。。。
                    QtGui.QMessageBox.warning(None, u'IP输入格式错误', u'校内IP必需以<font color=red>10.</font>开头，请检查您的输入', u'确定')
                    #self.ui.lE_proxy.set
                    del iplist
                    del ipstr
                    return
                elif not oneIP.replace('.', '').isdigit():#去掉. 检查是否全部为数字
                    QtGui.QMessageBox.warning(None, u'IP输入格式错误', u'IP必需由<font color=red>数字</font>和<font color=red>.</font>构成，请检查您的输入', u'确定')
                    del iplist
                    del ipstr
                    return
                elif 3 != oneIP.count('.'): #格式是否含有三个.
                    QtGui.QMessageBox.warning(None, u'IP输入格式错误', u'IP输入的格式必需为<font color=red>10.xx.xx.xx</font>', u'确定')
                    del iplist
                    del ipstr
                    return
                else:
                    ipSegmentsList = oneIP.split('.')
                    for ipSegment in ipSegmentsList: #校内IP中每个IP的每部分不能超过254
                        if 255 <= int(ipSegment):
                            QtGui.QMessageBox.warning(None, u'IP输入范围错误', u'校内IP地址中不能含有大于254的数字', u'确定')
                            del ipstr
                            del iplist
                            del ipSegmentsList
                            return
                   
            
            print iplist
            allowed = [] #运行的代理IP列表
            for name in iplist:
                client = socket.gethostbyname(name)
                allowed.append(client)
                print "Accept: %s (%s)" % (client, name)
            #TinyHTTPProxy.ProxyHandler.allowed_clients = allowed
            isProxy = True
            ip = checkNetwork_getIP()
            port = 1234
            serveraddr = ('', port)  #HTTP proxy Server info  IP: local ip, Port:1234
            global proxyS
            proxyS = TinyHTTPProxy.BaseHTTPServer.HTTPServer(serveraddr, TinyHTTPProxy.ProxyHandler)
            print "Starting proxy Server: IP:%s, PORT: %s" % (ip, port)
            global t_proxy
            t_proxy = MyThread(self.proxyServer, (allowed, proxyS))
            t_proxy.setDaemon(True)
            t_proxy.start()
            proxyCentent = u"开启HTTP代理成功!<br />现在您可以将<br /><font color=red>IP:%s端口:%s</font><br />告诉您的同学使用代理上网" % (ip, port)
            QtGui.QMessageBox.information(None, u"成功开启", proxyCentent, u"确定")
            self.ui.lE_proxy.setEnabled(False)
            self.ui.pB_proxy.setText(u"停止代理")
        elif isProxy:   
            print "Kill proxy.."
            isProxy = False
            t_proxy.kill() #停止代理监听进程
            proxyS.server_close() #关闭代理监听端口
            QtGui.QMessageBox.information(None, u"代理关闭", u"代理关闭成功", u"确定")
            self.ui.lE_proxy.setEnabled(True)
            self.ui.pB_proxy.setText(u"开启代理")
                     
    def proxyServer(self, allowedList, proxyS): #代理服务启动
        TinyHTTPProxy.ProxyHandler.allowed_clients = allowedList
        if isProxy:
            #TinyHTTPProxy.BaseHTTPServer.test(TinyHTTPProxy.ProxyHandler, TinyHTTPProxy.BaseHTTPServer.HTTPServer)
            proxyS.handle_request()
        else: # ??此代码好像没用，线程退出后，不会执行到这里
            print "isProxy=%s" % isProxy
            TinyHTTPProxy.BaseHTTPServer.server_close()
            sys.exit(1)
        


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    pypassport = QPyPassport()
    pypassport.show()
    sys.exit(app.exec_())
